<template>
  <div id="app" class="spare-part-list" tabindex="0">
    <!-- 头部导航 -->
    <van-nav-bar left-arrow title="备件跟踪" @click-left="comeBack" left-text="返回">
      <template #right>
        <!-- <div v-permissions="'61_471'" @click="onClickStart">盘点出库</div> -->
        <!--        <div @click="onClickScan">坯布扫码</div>-->
        <van-popover v-model="plus.show" theme="dark" trigger="click" :actions="plus.menu" placement="bottom-end" @select="selectPopMenuFn">
          <template #reference>
            <van-icon size="1.5rem" name="plus" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>

    <!-- 筛选 -->
    <van-search v-model="queryParam.keyLike" placeholder="请输入搜索关键词" @search="() => loadSparePartDataFn(1)" />

    <!-- 滚动 -->
    <better-scroll class="body-scroll" :data="sparePartData" :total-page="totalPage" :pulldown="true" :pullup="true" @pullup="loadNextPageFn" @pulldown="() => loadSparePartDataFn(1)">
      <van-swipe-cell v-show="sparePartData.length > 0" v-for="(row, rIndex) in sparePartData" :key="row.id" style="padding-bottom: 0.5rem">
        <template>
          <div class="data-card">
            <div style="flex: 0 0 18vw">
              <van-image width="15vw" height="12vh" fit="fill" :src="row.picView" @click="showPicPreViewFn(row)">
                <template v-slot:error>加载失败</template>
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>
            </div>
            <div style="flex: 1; flex-flow: column;">
              <div style="border-bottom: 1px solid #8191c5;" >
                <span style="color: #8191c5;font-size: 1.2rem; ">{{ row.name }}</span>
              </div>
              <div>
                <span style="color: #bb5a09;font-size: 1.1rem; ">{{ row.standard == SPLIT_BLANK ? "无规格" : row.standard }}</span>
              </div>
              <div>
                <span style="color: #232323;font-size: 1rem; ">{{ row.device }}</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #e6a23c">预计库存: {{ row.expectStock }} {{row.unit}}</span>
                <van-popover theme="dark" v-model="row.showArea" trigger="click" :actions="row.areas" placement="bottom-end" get-container="#app">
                  <template #reference>
                    <span style="color: #239a2a">库存: {{ row.stock }} {{row.unit}}</span>
                  </template>
                </van-popover>
              </div>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square size="small" type="warning" @click="showChangePicPopupFn(row)">上图</van-button>
            <van-button square style="margin-top: 1vh;" size="small" type="info" @click="showApplyForPopupFn(row)">采购申请</van-button>
            <van-button square style="margin-top: 1vh;" size="small" type="primary" @click="printLabel(row)">打印二维码</van-button>
          </div>
        </template>
      </van-swipe-cell>
      <van-empty  v-show="sparePartData.length == 0" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无数据" ></van-empty>
    </better-scroll>

    <!-- 上图弹窗 -->
    <van-popup v-model="showChangePicDialog" get-container="#app">
      <div style="width: 70vw; height: 60vh; overflow: auto">
        <van-uploader style="margin: 10px" preview-size="65vw" v-model="uploadFileList" :max-count="5"></van-uploader>
        <div style="margin: 16px;display: flex;justify-content: center;width: 90%;">
          <van-button block type="danger" native-type="button" @click="showChangePicDialog = false">取消</van-button>
          <van-button style="margin-left: 10vw;" block type="info" @click="confirmChangePicFn">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 打印弹窗 -->
<!--    <van-popup v-model="showPrintPopup">
      <div style="width: 50vw; height: 30vh;">
        <div>
          <van-field v-model="printNum" label="打印数量"></van-field>
        </div>
        <div style="margin: 16px;display: flex;justify-content: center;width: 90%;">
          <van-button block type="danger" native-type="button" @click="showPrintPopup = false">取消</van-button>
          <van-button style="margin-left: 10vw;" block type="info" @click="confirmPrintFn">确认打印</van-button>
        </div>
      </div>
    </van-popup>-->

    <!-- 操作弹窗 -->
<!--    <van-popup v-model="showOptPopup" get-container="#app">
      <div style="display: flex; width: 90vw; height: 10vh; padding-left: 2vw; padding-top: 1vh">
        <van-button type="warning">采购申请</van-button>
        <van-button type="info" style="margin-left: 5vw;">扫码入库</van-button>
        <van-button type="primary" style="margin-left: 5vw;">打印</van-button>
      </div>
    </van-popup>-->

    <!-- 图片预览 -->
    <van-image-preview v-model="showPicPreViewFlag" :showIndex="false" :closeable="true" :images="picPreView">
    </van-image-preview>

    <!-- 采购申请 -->
    <van-popup style="width: 70vw;padding: 1vh 2vw;" v-model="applyFor.show" get-container="#app">
      <div style="display: flex;justify-content: center;flex-flow: column">
        <van-field v-model="applyFor.num" label="申请数量" colon clearable required placeholder="请输入数字"></van-field>
        <van-field v-model="applyFor.remark" label="说明" colon clearable placeholder="请说明" type="textarea" :autosize="{minHeight: 50}"></van-field>
      </div>
      <div style="display: flex;justify-content: center;margin-top: 2vh;">
        <van-button size="small" block type="danger" native-type="button" @click="applyFor.show = false">取消</van-button>
        <van-button size="small" style="margin-left: 10vw;" block type="info" @click="confirmApplyForFn">确认</van-button>
      </div>
    </van-popup>

    <!-- 移区入库/退库/维修入库 弹窗 -->
    <van-popup style="width: 70vw;padding: 1vh 2vw;max-height: 50vh;overflow: auto;" v-model="scanChange.show" get-container="#app">
      <div style="display: flex;justify-content: center;font-size: 1.3rem;color: #1677FF;font-weight: bolder"><span>{{ plus.title }}</span></div>
      <div v-if="plus.opt == 3" style="color: #e6a23c;font-size: 1.2rem;" @click="scanWorkerFn">
        <span>退库人: {{ scanOut.taker }}</span>
      </div>
      <div style="color: #e6a23c;font-size: 1.2rem;">
        <van-field v-model="scanChange.defaultArea" readonly label="默认区域" colon @focus="() => showAreaPopupFn()"></van-field>
      </div>
      <van-swipe-cell v-if="scanChange.data.length > 0" v-for="(changeData, cIndex) in scanChange.data" :key="changeData.id" style="padding-bottom: 0.5rem">
        <template>
          <div v-if="scanChange.data.length > 0" style="display: flex;justify-content: center;flex-flow: column;box-shadow: 0.3rem 0.5rem 0.3rem #888888;margin-top: 0.5rem;">
            <div style="color: #8191c5;border-bottom: 1px solid #8191c5;" ><span>名称:{{ changeData.name }}</span></div>
            <div style="color: #bb5a09;"><span>规格:{{ changeData.standard }}</span></div>
            <div v-if="plus.opt == 1" style="color: #7de30e;" @click="showAreaPopupFn(changeData, true)"><span>源区域:{{ changeData.fromArea }}</span></div>
            <div style="color: #7de30e;" @click="showAreaPopupFn(changeData)"><span>目标区域:{{ changeData.area }}</span></div>
            <div v-if="plus.opt == 1 || plus.opt == 3">
              <van-field type="digit" v-model="changeData.num" label="数量"></van-field>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square style="margin-top: 1vh;" size="small" type="danger" @click="delChangeDetailFn(changeData, cIndex)">删除</van-button>
          </div>
        </template>
      </van-swipe-cell>
      <div style="display: flex;justify-content: center;margin-top: 2vh;">
        <van-button size="small" block type="danger" native-type="button" @click="resetScanFn">取消</van-button>
        <van-button size="small" style="margin-left: 5vw;" block type="primary" native-type="button" @click="openScanWinFn">扫码</van-button>
        <van-button size="small" style="margin-left: 5vw;" block type="info" @click="confirmChangeAreaFn">确认</van-button>
      </div>
    </van-popup>

    <!-- 扫码领用/回收处理 弹窗 -->
    <van-popup style="width: 70vw;padding: 1vh 2vw;max-height: 50vh;overflow: auto;" v-model="scanOut.show" get-container="#app">
      <div style="display: flex;justify-content: center;font-size: 1.3rem;color: #1677FF;font-weight: bolder"><span>{{ plus.title }}</span></div>
      <div v-if="plus.opt == 2" style="color: #e6a23c;font-size: 1.2rem;" @click="scanWorkerFn">
        <span>领料人: {{ scanOut.taker }}</span>
      </div>
      <van-swipe-cell v-if="scanOut.data.length > 0" v-for="(outData, oIndex) in scanOut.data" :key="outData.id" style="padding-bottom: 0.5rem">
        <template>
          <div v-if="scanOut.data.length > 0" style="display: flex;justify-content: center;flex-flow: column;box-shadow: 0.3rem 0.5rem 0.3rem #888888;margin-top: 0.5rem;">
            <div style="color: #8191c5;border-bottom: 1px solid #8191c5;" ><span>名称:{{ outData.name }}</span></div>
            <div style="color: #bb5a09;"><span>规格:{{ outData.standard }}</span></div>
            <div v-if="plus.opt == 2" style="color: #7de30e;" @click="showAreaPopupFn(outData, true)"><span>源区域:{{ outData.fromArea }}</span></div>
            <div v-if="plus.opt == 2">
              <van-field type="digit" v-model="outData.num" label="数量"></van-field>
            </div>
            <div v-if="plus.opt == 4" style="display:flex;justify-content: space-between;align-items: center; color: #e6a23c;font-size: 1.1rem;">
              <span>ID:{{ outData.id }}</span>
              <span>状态: {{ sparePartStatusEnumFn(outData.status) }}</span>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square style="margin-top: 1vh;" size="small" type="danger" @click="delOutDetailFn(outData, oIndex)">删除</van-button>
          </div>
        </template>
      </van-swipe-cell>
      <div style="display: flex;justify-content: center;margin-top: 2vh;">
        <van-button size="small" block type="danger" native-type="button" @click="resetScanFn">取消</van-button>
        <van-button size="small" style="margin-left: 5vw;" block type="primary" @click="openScanWinFn">扫码</van-button>
        <van-button size="small" style="margin-left: 5vw;" block type="info" @click="confirmScanOutFn">确认</van-button>
      </div>
    </van-popup>

    <!-- 区域弹窗 -->
    <van-popup v-model="area.show" position="bottom">
      <van-picker show-toolbar :columns="area.data" @confirm="selectAreaFn" @cancel="area.show = false">
        <template #title>
          <van-field style="width: 40vw;" v-model="area.keyLike" placeholder="输入关键字" @input="filterAreaFn"></van-field>
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script>
import {comeBack, openWin, randomStr} from "@/utils";
import {
  applyForSparePart, changeDetailArea,
  changeSparePartPic, filterSpareArea, handleRecycling, in4Unused,
  loadSparePartData, out4Usage, repairIn,
  sparePartDetail,
  sparePartDetailDetail
} from "@/views/spare-part/spare-part.js";
import {
  SPARE_PART_RECYCLING_ENUM,
  SPARE_PART_ROOM_ENUM,
  SPARE_PART_TYPE_ENUM,
  sparePartStatusEnumFn,
  SPLIT_BLANK,
  SPLIT_COMMA,
  SPLIT_YKH,
  SPLIT_ZKH
} from "@/api/enum";
import {getUploadKey} from "@/api/public";
import {picUpload} from "@/api/common";
import {exportBaseUrl} from "@/utils/request";
import {getInfo, getMacAddress} from "@/utils/auth";
import dayjs from "dayjs";
import {scanToLogin} from "@/api/login";

export default {
  name: "sparePartList",
  data() {
    return {
      SPLIT_ZKH, SPLIT_YKH, SPLIT_BLANK,

      /* 查询相关 */
      queryParam: {
        keyLike: "",
        pageNum: 1,
        pageSize: 10,
        partId: 0,
      },
      queryTimer: null,

      /* 列表相关 */
      sparePartData: [],
      totalPage: 0,
      uploadFileList: [],
      curRow: null,

      /* 图片相关 */
      picType: "WLBJ",
      showChangePicDialog: false,
      showPicPreViewFlag: false,
      picPreView: [],

      /* 打印相关 */
      // showPrintPopup: false,
      // printNum: 1,

      /* 操作相关 */
      // showOptPopup: false,

      /* 显示申请 */
      applyFor: {
        show: false,
        remark: SPLIT_BLANK,
        num: 1,
      },

      /* 加号菜单 */
      plus: {
        show: false,
        opt: 1,
        title: SPLIT_BLANK,
        menu: [{
          text: "扫码查询",
          icon: "scan"
        }, {
          text: "移区入库",
          icon: "exchange"
        }, {
          text: "领用出库",
          icon: "share-o"
        }, {
          text: "退库",
          icon: "replay"
        }, {
          text: "维修|卖钱",
          icon: "logistics"
        }, {
          text: "维修入库",
          icon: "shrink"
        }]
      },

      /* 区域弹窗 */
      area: {
        show: false,
        keyLike: SPLIT_BLANK,
        data: [],
        originalData: [],
      },

      /* 扫码移区 */
      scanChange: {
        show: false,
        sourceFlag: false,
        data: [],
        defaultArea: SPLIT_BLANK,
        curData: null,
      },

      /* 领用 */
      scanOut: {
        show: false,
        data: [],
        takerId: 0,
        taker: SPLIT_BLANK,
      }
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    comeBack, sparePartStatusEnumFn,

    /* 初始化 */
    initFn() {
      const that = this;
      if (getMacAddress()) {
        that.isEnabledBluetooth();
      } else {
        that.$toast.fail('如需打印，请退出登录选择打印机')
      }

      //加载区域数据
      filterSpareArea({}, data => {
        data.forEach(area => {
          that.area.originalData.push(area);
        });
      });

      //加载数据
      that.loadSparePartDataFn(1);
    },

    /* 加载备件 */
    loadSparePartDataFn(pageNum) {
      const that = this;
      if(pageNum == 1) {
        that.queryParam.pageNum = 1;
        that.sparePartData.splice(0, that.sparePartData.length);
      }

      loadSparePartData(that.queryParam, data => {
        if(!data.code && data.code != 0) {
          if(that.queryParam.partId > 0) {    //重置ID查询
            that.queryParam.partId = 0;
          }
          that.totalPage = data.totalPage;
          data.list.forEach(row => {
            that.fillPicViewFn(that, row);
            row.showArea = false;
            row.areas = row.areas.split(SPLIT_COMMA).map(area => {
              return {
                text: area
              }
            });
            that.sparePartData.push(row);
          });
        }
      });
    },
    /* 填充图片 */
    fillPicViewFn(that, row) {
      row.picView = "";
      getUploadKey({
        type: that.picType
      }, tokenRes => {
        row.picView = exportBaseUrl("res") + "/res_thumb/" + row.pic.split(SPLIT_COMMA)[0] + '?accessToken=' + tokenRes.accessToken;
      });
    },

    /* 加载下一页 */
    loadNextPageFn() {
      let that = this;
      that.queryParam.pageNum++;
      that.loadSparePartDataFn();
    },

    /* 显示更改图片窗口 */
    showChangePicPopupFn(row) {
      const that = this;
      that.curRow = row;
      that.uploadFileList.splice(0, that.uploadFileList.length);
      row.pic.split(SPLIT_COMMA).filter(pic => pic && SPLIT_BLANK != pic).forEach(pic => {
        getUploadKey({
          type: that.picType
        }, tokenRes => {
          that.uploadFileList.push({
            url: exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken,
            name: pic
          });
        });
      });
      that.showChangePicDialog = true;
    },

    /* 确认更改图片 */
    confirmChangePicFn() {
      const that = this;
      if(that.uploadFileList.length == 0) {
        that.$toast.fail("请上传图片");
        return false;
      }

      //上传图片
      picUpload(that, that.uploadFileList, res => {
        let tmpArray = that.uploadFileList.filter(uploadFile => uploadFile.name).map(uploadFile => uploadFile.name);
        tmpArray.push(res.data);
        changeSparePartPic({
          id: that.curRow.id,
          pic: tmpArray.join(SPLIT_COMMA)
        }, changeRes => {
          that.$toast.success("图片上传成功");
          that.showChangePicDialog = false;
          that.curRow.pic = tmpArray.join(SPLIT_COMMA);
          that.fillPicViewFn(that, that.curRow);
        });
      });
    },

    /* 显示预览图 */
    showPicPreViewFn(row) {
      const that = this;
      that.picPreView.splice(0, that.picPreView.length);
      row.pic.split(SPLIT_COMMA).forEach(pic => {
        getUploadKey({
          type: that.picType
        }, tokenRes => {
          that.picPreView.push(exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken);
        });
      });
      that.showPicPreViewFlag = true;
    },

    /* 显示打印对话框 */
    /*showPrintPopupFn(row) {
      const that = this;
      that.curRow = row;
      that.showPrintPopup = true;
    },*/
    /* 确认打印 */
    /*confirmPrintFn() {
      const that = this;
      for(let i=0; i<that.printNum; i++) {

      }
    },*/

    /* 显示操作弹窗 */
    /*showOptPopupFn(row) {
      const that = this;
      that.curRow = row;
      that.showOptPopup = true;
    },*/

    /* 采购申请 */
    showApplyForPopupFn(row) {
      const that = this;
      that.curRow = row;
      that.applyFor.show = true;
    },
    /* 确认申请 */
    confirmApplyForFn() {
      const that = this;
      if(that.applyFor.num > 0) {
        applyForSparePart({
          partId: that.curRow.id,
          num: that.applyFor.num
        }, () => {
          that.$toast.success({
            message: "申请成功",
            onClose: () => {
              that.applyFor.show = false;
              that.applyFor.num = 1;
              that.applyFor.remark = SPLIT_BLANK;
              openWin("spare-part-apply-for");
            }
          });
        });
      } else {
        that.$toast.fail("请输入有效数字");
      }
    },

    /* 选中菜单 */
    selectPopMenuFn(action, index) {
      const that = this;
      that.plus.opt = index;
      that.plus.title = action.text;
      let msg = "请扫 备件大码";
      if(that.plus.opt == 2 || that.plus.opt == 4 ||  that.plus.opt == 5) {
        msg = "请扫 详情小码";
      }

      that.$toast.loading({
        message: msg,
        onClose: () => {
          if(that.plus.opt  == 1 || that.plus.opt == 3 || that.plus.opt == 5) {
            that.scanChange.show = true;
          } else {
            that.openScanWinFn();
          }
        }
      });
    },

    /* 显示区域弹窗 */
    showAreaPopupFn(changeData, sourceFlag) {
      const that = this;
      that.area.data.splice(0, that.area.data.length);
      that.scanChange.curData = changeData;
      if(sourceFlag) {
        that.scanChange.sourceFlag = true;
        filterSpareArea({
          partId: that.scanChange.curData.partId,
          keyLike: that.area.keyLike
        }, data => {
          data.forEach(area => {
            that.area.data.push(area);
          });
          that.area.show = true;
        });
      } else {
        that.area.originalData.forEach(area => {
          that.area.data.push(area);
        });
        that.area.show = true;
      }
    },

    /* 过滤区域 */
    filterAreaFn() {
      const that = this;
      clearTimeout(that.queryTimer);
      that.queryTimer = setTimeout(() => {
        that.area.data.splice(0, that.area.data.length);
        if(that.scanChange.sourceFlag) {
          filterSpareArea({
            partId: that.scanChange.partId,
            keyLike: that.area.keyLike
          }, data => {
            data.forEach(area => {
              that.area.data.push(area);
            });
          });
        } else {
          that.area.originalData.filter(area => area.indexOf(that.area.keyLike) != -1).forEach(area => {
            that.area.data.push(area);
          });
        }
        that.area.show = true;
      }, 1500);
    },

    /* 选择区域 */
    selectAreaFn(area) {
      const that = this;
      if(that.scanChange.curData) {
        if(that.scanChange.sourceFlag) {
          that.scanChange.curData.fromArea = area;
        } else {
          that.scanChange.curData.area = area;
        }
      } else {
        that.scanChange.defaultArea = area;
      }
      that.area.show = false;
    },

    /* 打开扫码窗 */
    openScanWinFn() {
      const that = this;

      if((that.plus.opt == 1 || that.plus.opt == 3 || that.plus.opt == 5) && that.scanChange.defaultArea == SPLIT_BLANK) {
        that.$toast.fail("请先选择目标区域");
        return;
      } else if(that.plus.opt == 2 || that.plus.opt == 4) {
        that.scanOut.show = true;
      }

      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          if(ret.result.indexOf("33,") == 0) {    //备件码
            let ids = ret.result.split(SPLIT_COMMA);
            if(ids.length != 2) {
              that.$toast.fail("二维码异常");
              return;
            }
            that.queryParam.partId = ids[1];
            if(that.plus.opt == 0) {   //查询
              that.loadSparePartDataFn(1);
            } else {
              sparePartDetail({
                partId: ids[1]
              }, data => {
                let msg = "扫码成功";
                if(that.plus.opt == 1 || that.plus.opt == 3) {    //扫码移区|退库
                  let changeData = that.scanChange.data.find(changeData => changeData.partId == data.id);
                  if(!changeData) {
                    that.scanChange.data.push({
                      partId: data.id,
                      name: data.name,
                      standard: data.standard,
                      fromArea: SPLIT_BLANK,
                      area: that.scanChange.defaultArea,
                      num: 1
                    });
                  } else {
                    msg = "已扫码过";
                  }
                } else if(that.plus.opt == 2) {    //领用出库
                  let outData = that.scanOut.data.find(outData => outData.partId == data.id);
                  if(!outData) {
                    that.scanOut.data.push({
                      partId: data.id,
                      name: data.name,
                      standard: data.standard,
                      fromArea: SPLIT_BLANK,
                      num: 1,
                    });
                  } else {
                    msg = "已扫码过";
                  }
                }
                that.$toast.success({
                  message: msg,
                });
              });
            }
          } else if(ret.result.indexOf("34,") == 0) {   //扫详情码
            let ids = ret.result.split(SPLIT_COMMA);
            if(ids.length != 3) {
              that.$toast.fail("二维码异常");
              return;
            }
            that.queryParam.partId = ids[1];
            if(that.plus.opt == 0) {   //查询
              that.loadSparePartDataFn(1);
            } else if(that.plus.opt == 5) {    //维修入库
              sparePartDetailDetail({
                detailId: ids[2]
              }, data => {
                let changeData = that.scanChange.data.find(changeData => changeData.id == data.id);
                let msg = "扫码成功,请继续";
                if(!changeData) {
                  that.scanChange.data.push({
                    id: data.id,
                    partId: data.partId,
                    name: data.name,
                    standard: data.standard,
                    area: that.scanChange.defaultArea,
                  });
                } else {
                  msg = "已扫码过,请继续";
                }
                that.$toast.success({
                  message: msg,
                  onClose: () => {
                    that.openScanWinFn();
                  }
                });
              });
            } else if(that.plus.opt == 4) {    //回收处理
              sparePartDetailDetail({
                detailId: ids[2],
              }, data => {
                let outData = that.scanOut.data.find(outData => outData.id == data.id);
                let msg = "扫码成功,请继续";
                if(that.plus.opt == 4 && data.status != 8 && data.status != 9) {    //回收处理: 8-待卖掉 9-待维修
                  msg = "该备件不是待处理状态,请扫其他备件";
                } else if(!outData) {
                  that.scanOut.data.push({
                    id: data.id,
                    partId: data.partId,
                    name: data.name,
                    standard: data.standard,
                    area: data.area,
                    status: data.status,
                  });
                } else {
                  msg = "已扫码过,请继续";
                }
                that.$toast.success({
                  message: msg,
                  onClose: () => {
                    that.openScanWinFn();
                  }
                });
              });
            } else {
              that.$toast.fail("不支持的操作");
            }
          } else {
            that.$toast.fail("不支持的二维码");
          }
        }
      });
    },

    /* 扫描员工码 */
    scanWorkerFn() {
      const that = this;
      that.$toast({
        type: "loading",
        message: "请扫领料员工二维码",
        overlay: true,
        forbidClick: true,
        duration: 1500,
        onClose: () => {
          const zyHmsScan = api.require('zyHmsScan');
          zyHmsScan.openDefaultView({}, ret => {
            if (ret.status) {
              if(ret.result.indexOf(",type=login,") != -1) {
                let infos = ret.result.split(",type=login,");
                scanToLogin({
                  no: infos[0],
                  pwd: infos[1],
                  platform: 3,
                  captcha: randomStr(),
                }, loginRes => {
                  that.scanOut.takerId = loginRes.userId;
                  that.scanOut.taker = loginRes.realName;
                });
              } else {
                that.$toast.fail("请扫员工码");
              }
            }
          });
        },
      });
    },

    /* 删除移区扫码 */
    delChangeDetailFn(changeData, cIndex) {
      const that = this;
      that.scanChange.data.splice(cIndex, 1);
    },

    /* 确认入库 */
    confirmChangeAreaFn() {
      const that = this;
      if(that.scanChange.data.length == 0) {
        that.$toast.fail("请先扫备件码");
        return;
      }
      that.scanChange.data.forEach(inData => {
        inData.takerId = that.scanOut.takerId;
        inData.taker = that.scanOut.taker;
      });
      if(that.plus.opt == 1) {    //移区入库
        changeDetailArea(that.scanChange.data, () => {
          that.$toast.success({
            message: "移区成功",
            onClose: that.resetScanFn()
          });
        });
      } else if(that.plus.opt == 3) {   //退库入库
        in4Unused(that.scanChange.data, () => {
          that.$toast.success({
            message: "入库成功",
            onClose: that.resetScanFn()
          });
        });
      } else if(that.plus.opt == 5) {   //维修入库
        repairIn(that.scanChange.data, () => {
          that.$toast.success({
            message: "入库成功",
            onClose: that.resetScanFn()
          });
        });
      }
    },

    /* 重置扫码 */
    resetScanFn() {
      const that = this;
      that.scanChange.show = false;
      that.scanChange.sourceFlag = false;
      that.scanChange.data.splice(0, that.scanChange.data.length);
      that.scanChange.curData = null;
      that.scanOut.show = false;
      that.scanOut.data.splice(0, that.scanOut.data.length);
      that.scanOut.takerId = 0;
      that.scanOut.taker = SPLIT_BLANK;
    },

    /* 删除出库扫码 */
    delOutDetailFn(outData, oIndex) {
      const that = this;
      that.scanOut.data.splice(oIndex, 1);
    },

    /* 确认出库 */
    confirmScanOutFn() {
      const that = this;
      if(that.scanOut.data.length == 0) {
        that.$toast.fail("请先扫备件码");
        return;
      }
      //赋值领料人
      that.scanOut.data.forEach(outData => {
        outData.takerId = that.scanOut.takerId;
        outData.taker = that.scanOut.taker;
      });
      if(that.plus.opt == 2) {    //领用出库
        out4Usage(that.scanOut.data, () => {
          that.$toast.success({
            message: "领用成功",
            onClose: () => {
              that.scanOut.show = false;
              that.scanOut.data.splice(0, that.scanOut.data.length);
            }
          });
        });
      } else if(that.plus.opt == 4) {
        handleRecycling(that.scanOut.data, () => {
          that.$toast.success({
            message: "处理成功",
            onClose: () => {
              that.scanOut.show = false;
              that.scanOut.data.splice(0, that.scanOut.data.length);
            }
          });
        });
      }
    },

    /* 判断蓝牙是否打开 */
    isEnabledBluetooth() {
      const that = this;
      window.api.require("cxgBluetoothBase").isEnabledBluetooth({}, (ret, err) => {
        if (!err) {
          if (ret.state) {
            // 已打开
            that.connectBleByMacAddress();
          } else {
            that.openBluetooth();
          }
        } else {
          that.$toast.fail("code: " + err.code + " msg: " + err.msg);
        }
      });
    },
    /* 打开蓝牙 */
    openBluetooth() {
      const that = this;
      window.api.require("cxgBluetoothBase").openBluetooth({}, function (ret, err) {
        if (!err) {
          if (ret.state) {
            // 已打开
            that.connectBleByMacAddress();
          }
        } else {
          that.listenBluetoothStatus();
        }
      });
    },
    /* 监听蓝牙连接状态 */
    listenBluetoothStatus() {
      const that = this;
      window.api.require("cxgBluetoothBase").listenBluetoothStatus({}, function (ret, err) {
        if (!err) {
          if (ret.status === "STATE_ON") {
            that.connectBleByMacAddress();
          }
        } else {
          that.$toast.fail("code: " + err.code + " msg: " + err.msg);
        }
      });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      let obj = window.api.require("xGprinterPlus");
      let ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    /* 连接蓝牙 */
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      let demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress({
        macAddress:  getMacAddress() ? getMacAddress().address : '',
      }, (ret, err) => {
        if (ret.status) {
          if (ret.message === "已连接") {
            that.connectionStatus = true;
            if (that.printStatus) {
              that.$toast({
                type: "success",
                message: "连接成功",
                duration: 1500,
              });
            }
            if (status) {
              // that.onClickAddStore();    //新增盘库?
            }
          } else if (ret.message === "连接失败") {
            that.connectionStatus = false;
            that.$toast({
              type: "fail",
              message: "初始化失败",
              duration: 1500,
            });
          } else {
            that.connectionStatus = false;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.msg,
            duration: 1500,
          });
        }
      });
    },
    /* 打印数据 */
    printLabel(data) {
      const that = this;
      let obj = window.api.require("xGprinterPlus");
      let rows = [{
        lineType: "size",
        width: 50,
        height: 70,
      }, {
        lineType: "gap",
        data: 3,
      }, {
        lineType: "cls",
      }, {
        // 图片单元格竖线
        lineType: "bar",
        x: 25 + 150,
        y: 0,
        width: 2,
        height: 136,
      }, {
        //绘制图片
        lineType: "image",
        x: 25 + 8,
        y: 8,
        data: "widget://image/huibo_logo.png",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 10,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "艺多染整",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 60,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "备件规格码",
      }, {
        lineType: "qrcode", // 绘制qrcode
        x: 25 + 170 + 2,
        y: 10,
        level: "L", //L|M|H|Q
        cellwith: 8,
        rotation: 0, // 0|90|180|270
        data: "33," + data.id,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 136 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "ID:" + data.id,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 186,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 186 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "类型: " + SPARE_PART_TYPE_ENUM[data.type],
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 236,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 236 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "车间:" + SPARE_PART_ROOM_ENUM[data.room],
      }, {
        //绘制文本
        lineType: "text",
        x: 300 + 4,
        y: 236 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: SPARE_PART_RECYCLING_ENUM[data.recyclingFlag],
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 286,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 286 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "用途: " + data.device,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 336 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "名称: " + data.name,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 336,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 386 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "规格: " + data.standard,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 386,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 436 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "打印人: " + getInfo().realName,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 436,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 516 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "打印日期: " + dayjs().format("YYYY-MM-DD"),
      },];
      obj.printLabel({
        rows: rows,
      }, (ret, err) => {
        if (ret.status) {
          that.$toast.success("打印成功");
          --that.printCount;
          if (that.printCount > 0) {
            that.printLabel(data);
          } else {
            that.printCount = 1;

            //关闭盘库窗口
            that.showCheck = false;
          }
        } else {
          that.$toast({
            type: "fail",
            message: err.code + err.msg,
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.spare-part-list {
  height: 100%;
  ::v-deep .van-search {
    z-index: 1;
  }

  .body-scroll {
    height: 79vh;
    .data-card {
      width: 96vw;
      padding: 0 0.8rem;
      margin-left: 2vw;
      background-color: white;
      margin-top: 0.5rem;
      box-shadow: 0.3rem 0.5rem 0.3rem #888888;
      display: flex;
      div {
        display: flex;
        padding: 0.3rem 0rem;
        span {
          line-height: 1rem;
        }
      }
    }
  }

  ::v-deep .van-popover__action {
    width: 50vw;
  }
}
</style>